#!/bin/bash

if [[ $# -ne 2 ]]; then
    echo "The format is as follows:"
    echo "./ucsc_tools.sh buildpath installpath"
    echo ":param buildpath: 应用构建绝对路径"
    echo ":param installpath: 应用安装绝对路径"
    exit 1
fi

if [[ ! "$1" =~ ^/.* || ! -d "$1" || "$1" = "/" ]]; then echo "请输入正确的构建路径"; exit 1; fi
if [[ ! "$2" =~ ^/.* || ! -d "$2" || "$2" = "/" ]]; then echo "请输入正确的安装路径"; exit 1; fi
[[ "$1" = "$2" ]] && echo "构建路径与安装路径不能相同" && exit 1
buildpath=$1
installpath=$2
if [[ "$1" =~ .*/$ ]]; then buildpath=${buildpath%/*}; fi
if [[ "$2" =~ .*/$ ]]; then installpath=${installpath%/*}; fi

yum install libpng libpng-devel libuuid-devel -y
wget -t 10 -c -P $buildpath/ucsc_tools https://hgdownload.soe.ucsc.edu/admin/jksrc.zip	
cd $buildpath/ucsc_tools
unzip jksrc.zip
MACHTYPE=aarch64 && mkdir -p ~/bin/$MACHTYPE
cd kent/src/lib
sed -i -e '714c if (format != NULL)' htmshell.c
sed -i -e '1c CC=clang' ../inc/localEnvironment.mk
make -j$(nproc)
cd ../jkOwnLib && make -j$(nproc) CC=clang
cd ../htslib && make -j$(nproc) CC=clang
cd ../utils/faToTwoBit && make -j$(nproc) CC=clang
cd ../twoBitInfo && make -j$(nproc) CC=clang
cd ../twoBitToFa && make -j$(nproc) CC=clang
cp -r ~/bin/$MACHTYPE $installpath/ucsc_tools
cat>"$installpath/ucsc_tools/ucsc_tools_modulefiles"<<EOF
#%Module1.0
conflict ucsc_tools
variable modfile [file normalize [info script]]
proc getModulefileDir {} {
    variable modfile
    set modfile_path [file dirname \$modfile]
    return \$modfile_path
}
set pwd [getModulefileDir]
set ucsc_tools \$pwd
setenv ucsc_tools \$ucsc_tools
prepend-path PATH \$ucsc_tools
EOF
